import { ModalForm } from '@ant-design/pro-form';
import type { FormInstance } from 'antd';
import { Collapse, Checkbox, message } from 'antd';
import { useRef } from 'react';
import CollapsePanel from 'antd/lib/collapse/CollapsePanel';
import { useModel } from 'umi';
import type { CheckboxChangeEvent } from 'antd/lib/checkbox';
import styles from '../style.less';
import { CaretRightFilled } from '@ant-design/icons';
import { getAuthById, updateAuthById } from '../service';
import { Auths } from '@/utils/typings.d';
import { EMPTYAUTH } from '../typings.d';
import { useAuthVariable } from '../hooks/useAuthVariable';

interface AuthSettingProps {
  authId: string;
  ownerName: string;
}

const CheckboxGroup = Checkbox.Group;

export default (props: AuthSettingProps) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const CURRAUTH: USER.AuthType = currUser?.auth || EMPTYAUTH;
  // TODO: 扩展权限

  const OPER_SYSTEMUSER = CURRAUTH.systemUser || [];
  const OPER_SYSRECORD = CURRAUTH.systemLog || [];
  const OPER_IOTSIM = CURRAUTH.iotSim || [];
  const OPER_SYSTEMWARNING = CURRAUTH.systemWarning || [];
  const OPER_LOGISTICS = CURRAUTH.logistics || [];

  const { authId, ownerName } = props;
  const systemSettingRef = useRef<FormInstance>();

  // systemUser
  const systemUser = useAuthVariable(OPER_SYSTEMUSER);

  // systemLog
  const systemLog = useAuthVariable(OPER_SYSRECORD);

  // iotSim
  const iotSim = useAuthVariable(OPER_IOTSIM);

  // systemWarning
  const systemWarning = useAuthVariable(OPER_SYSTEMWARNING);

  // logistics
  const logistics = useAuthVariable(OPER_LOGISTICS);

  const onChange = (list: any[], authVariable: AuthVariable) => {
    let tempList = list;
    if (!list.includes(Auths.READ)) {
      message.warn({ content: '无法在无 [查看] 权限时，操作模块', key: 'read_error' });
      authVariable.setEnable(true);
      tempList = [];
    } else {
      authVariable.setEnable(false);
    }
    authVariable.setList(tempList);
    authVariable.setIntermin(!!tempList.length && tempList.length < authVariable.auth.length);
    authVariable.setCheckAll(tempList.length === authVariable.auth.length);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent, authVariable: AuthVariable) => {
    authVariable.setList(
      e.target.checked ? authVariable.auth.map((item: { value: any }) => item.value) : [],
    );
    authVariable.setIntermin(false);
    authVariable.setEnable(!e.target.checked);
    authVariable.setCheckAll(e.target.checked);
  };

  const simplyInit = (authVariable: AuthVariable, dataList: Auths[] = []) => {
    if (dataList.length === 0) {
      authVariable.setIntermin(false);
      authVariable.setEnable(true);
    } else if (dataList.length === authVariable.auth.length) {
      authVariable.setIntermin(false);
      authVariable.setCheckAll(true);
    }
  };

  return (
    <ModalForm
      formRef={systemSettingRef}
      width={700}
      modalProps={{
        destroyOnClose: true,
      }}
      title={
        <div>
          权限配置<small style={{ color: '#bbb' }}>（{ownerName}）</small>
        </div>
      }
      trigger={
        <a
          onClick={async () => {
            const { data } = await getAuthById(authId);
            systemUser.setList(data.systemUser);
            systemLog.setList(data.systemLog);
            iotSim.setList(data.iotSim);
            systemWarning.setList(data.systemWarning);
            logistics.setList(data.logistics);
            // 用户
            simplyInit(systemUser, data.systemUser);
            // 系统日志
            simplyInit(systemLog, data.systemLog);
            // 流量卡
            simplyInit(iotSim, data.iotSim);
            // 系统告警
            simplyInit(systemWarning, data.systemWarning);
            // 物流
            simplyInit(logistics, data.logistics);
          }}
        >
          权限配置
        </a>
      }
      onFinish={async () => {
        const res = await updateAuthById(authId, {
          systemUser: systemUser.list,
          systemLog: systemLog.list,
          iotSim: iotSim.list,
          systemWarning: systemWarning.list,
          logistics: logistics.list,
        });
        if (res.success) {
          message.success({ content: res.message, key: 'auth_msg' });
          return true;
        }
        message.error({ content: res.message, key: 'auth_msg' });
        return false;
      }}
    >
      <Collapse
        bordered={false}
        className={styles.mycollapse}
        expandIcon={({ isActive }) => <CaretRightFilled rotate={isActive ? 90 : 0} />}
        defaultActiveKey={[]}
        accordion
      >
        {OPER_IOTSIM.length && (
          <CollapsePanel
            className={styles.mypanel}
            header={
              <Checkbox
                indeterminate={iotSim.intermin}
                onChange={(e) => {
                  onCheckAllChange(e, iotSim);
                }}
                checked={iotSim.checkAll}
                onClick={(e) => e.stopPropagation()}
              >
                流量卡
              </Checkbox>
            }
            key="iotSim"
          >
            <CheckboxGroup
              options={iotSim.auth}
              name="iotSim"
              value={iotSim.list}
              onChange={(list) => {
                onChange(list, iotSim);
              }}
            />
          </CollapsePanel>
        )}
        {OPER_LOGISTICS.length && (
          <CollapsePanel
            className={styles.mypanel}
            header={
              <Checkbox
                indeterminate={logistics.intermin}
                onChange={(e) => {
                  onCheckAllChange(e, logistics);
                }}
                checked={logistics.checkAll}
                onClick={(e) => e.stopPropagation()}
              >
                物流模块
              </Checkbox>
            }
            key="logistics"
          >
            <CheckboxGroup
              options={logistics.auth}
              name="logistics"
              value={logistics.list}
              onChange={(list) => {
                onChange(list, logistics);
              }}
            />
          </CollapsePanel>
        )}
        {OPER_SYSTEMWARNING.length && (
          <CollapsePanel
            className={styles.mypanel}
            header={
              <Checkbox
                indeterminate={systemWarning.intermin}
                onChange={(e) => {
                  onCheckAllChange(e, systemWarning);
                }}
                checked={systemWarning.checkAll}
                onClick={(e) => e.stopPropagation()}
              >
                系统告警
              </Checkbox>
            }
            key="systemWarning"
          >
            <CheckboxGroup
              options={systemWarning.auth}
              name="systemWarning"
              value={systemWarning.list}
              onChange={(list) => {
                onChange(list, systemWarning);
              }}
            />
          </CollapsePanel>
        )}
        {OPER_SYSTEMUSER.length && (
          <CollapsePanel
            className={styles.mypanel}
            header={
              <Checkbox
                indeterminate={systemUser.intermin}
                onChange={(e) => {
                  onCheckAllChange(e, systemUser);
                }}
                checked={systemUser.checkAll}
                onClick={(e) => e.stopPropagation()}
              >
                用户模块
              </Checkbox>
            }
            key="systemUser"
          >
            <CheckboxGroup
              options={systemUser.auth}
              name="systemUser"
              value={systemUser.list}
              onChange={(list) => {
                onChange(list, systemUser);
              }}
            />
          </CollapsePanel>
        )}
        {OPER_SYSRECORD.length && (
          <CollapsePanel
            className={styles.mypanel}
            header={
              <Checkbox
                indeterminate={systemLog.intermin}
                onChange={(e) => {
                  onCheckAllChange(e, systemLog);
                }}
                checked={systemLog.checkAll}
                onClick={(e) => e.stopPropagation()}
              >
                系统日志
              </Checkbox>
            }
            key="systemLog"
          >
            <CheckboxGroup
              options={systemLog.auth}
              name="systemLog"
              value={systemLog.list}
              onChange={(list) => {
                onChange(list, systemLog);
              }}
            />
          </CollapsePanel>
        )}
      </Collapse>
    </ModalForm>
  );
};
